package com.emenu;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;

import com.emenu.R.color;
import com.emenu.application.StaticObject;
import com.emenu.bean.BusHitDetail;
import com.emenu.bean.BusSerieshit;
import com.emenu.bean.Menu;
import com.emenu.bean.PubSeries;
import com.emenu.bean.PubSeriesGroup;
import com.emenu.bean.StackBean;
import com.emenu.bean.SubMenu;
import com.emenu.bean.User;
import com.emenu.common.SaveMenuImg;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;

public class FragmentSetMeal extends Fragment {
	private String submenu_code;
	private List<SubMenu> sublist = new ArrayList<SubMenu>();
	// 存放checkbox里选中的菜品code（）submenu_code
	// 所点套餐明细
	// private List seriessunlist = new ArrayList();
	// 临时保存已经点了套餐的明细，
	private List<BusSerieshit> bshlist = new ArrayList<BusSerieshit>();
	private String SDPATH;
	private SubMenu sm = new SubMenu();
	public StaticObject SO;

	Bitmap bm;

	TableLayout table;

	private Button mealleft;
	private ImageView meal_img;
	private Button mealright;
	private TextView mealintroduce_dtl;

	private TextView mealprice;
	private TextView mealindex;
	private TextView meal_today_hit;
	private TextView meal_his;

	private EditText meal_amount;
	private Button meal_post;

	List<BusHitDetail> bhdList;

	Context cn;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.setmeal, container, false);
		table = (TableLayout) v.findViewById(R.id.mealtable);

		SDPATH = Environment.getExternalStorageDirectory() + File.separator
				+ "Picture" + File.separator;

		findViewsById(v);
		setListener();

		meal_amount.setText((int) getArguments().getDouble("amount") + "");

		showImg(sm);
		appendRow(table);

		return v;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		submenu_code = getArguments().getString("code");

		for (SubMenu smenu : SO.getSubMenuList()) {
			if (smenu.getCode() == submenu_code) {
				sm = smenu;
			}
			if (smenu.getIs_Serise() == 1) {
				sublist.add(smenu);

			}
		}
		StackBean sb = new StackBean();
		sb.setName(sm.getName());
		SO.getStackList().add(sb);

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		((FragmentMAin) cn).showpath();
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		SO = (StaticObject) activity.getApplication();
		cn = this.getActivity();
		bhdList = SO.getBusHitDetailList();
	}

	private void findViewsById(View v) {
		
		meal_img = (ImageView) v.findViewById((R.id.meal_img));
		mealleft = (Button) v.findViewById((R.id.mealleft));
		mealright = (Button) v.findViewById((R.id.mealright));
		meal_post = (Button) v.findViewById((R.id.mealpost));
		mealintroduce_dtl = (TextView) v.findViewById((R.id.mealintroduce_dtl));
		mealprice = (TextView) v.findViewById((R.id.mealprice));
		mealindex = (TextView) v.findViewById((R.id.mealindex));
		meal_today_hit = (TextView) v.findViewById((R.id.meal_today_hit));
		meal_his = (TextView) v.findViewById((R.id.meal_his));
		meal_amount = (EditText) v.findViewById((R.id.meal_amount));

	}

	/** 设置监听器 */
	private void setListener() {
		mealleft.setOnClickListener(leftimg);
		mealright.setOnClickListener(rightimg);
		meal_post.setOnClickListener(post);
	}

	private OnClickListener leftimg = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (null != bm && !bm.isRecycled()) {
				bm.recycle();
			}
			// 当前对象的索引
			int i = sublist.indexOf(sm);

			if (i > 0) {
				sm = sublist.get(i - 1);
				showImg(sm);
			}

		}
	};
	private OnClickListener rightimg = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (null != bm && !bm.isRecycled()) {
				bm.recycle();
			}
			// 当前对象的索引
			int i = sublist.indexOf(sm);

			if (i < sublist.size()) {
				sm = sublist.get(i + 1);
				showImg(sm);
			}
		}
	};
	// 点菜
	private OnClickListener post = new OnClickListener() {

		@Override
		public void onClick(View v) {

			int ha = (int) (Double.parseDouble(String.valueOf(meal_amount
					.getText())));

			int itemp = 0;
			// 原来已点过该菜品，直接在全局list里把该菜品数量加1
			for (BusHitDetail bhd : bhdList) {

				if (bhd.getMenucode().equals(sm.getCode())) {
					// 套餐点菜单记录加所点数量
					bhd.setAmount(Math.round(bhd.getAmount() + ha));
					// 套餐明细bshlist不变
					itemp = 1;
					break;
				}
			}
			// 原来未点过该菜品，list里新加入该条记录
			if (itemp != 1) {
				BusHitDetail bhd = new BusHitDetail();
				bhd.setBig_Menu_code(sm.getMenu_code());
				bhd.setID(-1);
				bhd.setHit_code("-1");
				bhd.setMenucode(sm.getCode());
				bhd.setMenuname(sm.getName());
				bhd.setPrice(sm.getPrice());
				bhd.setAmount(ha);
				bhd.setTag_code(sm.getTag_code());
				bhd.setTag_name(sm.getTag_name());
				bhd.setAmount_sum(Math.round(sm.getPrice() * ha));
				bhd.setMenu_type("-1");
				bhd.setRljtype(sm.getRljtype());
				bhd.setCalledSingle(0);
				bhd.setRemark("");
				bhd.setUpload(0);
				bhd.setC1("");
				bhd.setC2("");
				bhd.setC3("");

				bhdList.add(bhd);
				SO.setBusHitDetailList(bhdList);
			}

			// 加入套餐明细
			if (bshlist != null) {
				if (SO.getBusSerieshitList().size() < 1) {
					// bshlist传值给SO，非引用
					for (BusSerieshit bstemp : bshlist) {
						BusSerieshit bbb = new BusSerieshit();
						bbb.setId(bstemp.getId());
						bbb.setHit_code(bstemp.getHit_code());
						bbb.setSeries_code(bstemp.getSeries_code());
						bbb.setSeriesgroupcode(bstemp.getSeriesgroupcode());
						bbb.setSubmenu_code(bstemp.getSubmenu_code());
						bbb.setAmount(bstemp.getAmount());
						bbb.setUpload(bstemp.getUpload());
						bbb.setC1(bstemp.getC1());
						bbb.setC2(bstemp.getC2());
						bbb.setC3(bstemp.getC3());

						SO.getBusSerieshitList().add(bbb);
					}
				} else {
					for (BusSerieshit bsh : bshlist) {
						// 标示位，全局变量里是否有该条记录
						int k = 0;

						for (BusSerieshit bseh : SO.getBusSerieshitList()) {
							if (bseh.getSubmenu_code().equals(
									bsh.getSubmenu_code())) {

								double dh = bsh.getAmount();
								double de = bseh.getAmount();
								double mt = Double.parseDouble(meal_amount
										.getText() + "");

								bseh.setAmount((int) (de + dh * mt));

								k = 1;
								break;
							}

						}
						if (k == 0) {
							SO.getBusSerieshitList().add(bsh);
						}

					}
				}

			}
			// 右边菜类列表数量变化
			for (Menu mu : SO.getMenuList()) {

				if (mu.getCode().equals(sm.getMenu_code())) {
					mu.setCount(mu.getCount() + ha);
				}
				if (mu.getC1() == sm.getRljtype()) {
					mu.setCount(mu.getCount() + ha);
				}
			}
			((FragmentMAin) cn).refreshRight();
		}
	};

	public void showImg(SubMenu sum) {

		String fileName = SDPATH + SaveMenuImg.getpath(sum.getPicpath())
				+ sum.getName() + ".jpg";
		bm = BitmapFactory.decodeFile(fileName);

		meal_img.setImageBitmap(bm);
		mealintroduce_dtl.setText(sm.getRemark());
		mealprice.setText(sm.getPrice() + "/" + sm.getTag_name());
		mealindex.setText(sm.getHitamount() + "");

		// 显示套餐下的套餐组

	}

	private void appendRow(final TableLayout table) {

		// 保存存套餐里的套餐组编码——用来计算每个套餐组下的菜品数量
		List<String> listcode = new ArrayList<String>();

		// 存非重复套餐组-用来循环显示在视图
		Set<String> set = new HashSet<String>();
		for (PubSeries ps : SO.getPubSeriesList()) {
			if (ps.getSeries_code().equals(sm.getCode())) {
				// 保存非重复记录到set
				set.add(ps.getSeriesgroupcode());
				listcode.add(ps.getSeriesgroupcode());
			}
		}

		// 取非重复套餐组
		Iterator<String> iter = set.iterator();

		while (iter.hasNext()) {
			String gp = iter.next();

			// 显示套餐组
			for (final PubSeriesGroup psg : SO.getPubSeriesGroupList()) {

				if (psg.getCode().equals(gp)) {

					TableRow row = new TableRow(cn);
					// row.setBackgroundColor(R.color.left_bg);

					ImageView iv = new ImageView(cn);
					iv.setBackgroundColor(R.color.verline);
					// iv.setLayoutParams(new LayoutParams(20, 2) );

					// 套餐组有几个菜品
					int subcount = Collections.frequency(listcode, gp);
					// 套餐组名称
					TextView grpview = new TextView(cn);
					grpview.setGravity(Gravity.CENTER);
					grpview.setTextColor(R.color.loginbgcol);
					grpview.setText(psg.getName());
					grpview.setPadding(3, 3, 3, 3);

					// 套餐组选择方式3选2，
					TextView grpselect = new TextView(cn);
					grpselect.setGravity(Gravity.CENTER);
					grpselect.setTextColor(R.color.loginbgcol);
					grpselect.setText(subcount + "选"
							+ (int) psg.getSelectcount());
					grpselect.setPadding(3, 3, 3, 3);

					// 取菜品
					TableLayout to = new TableLayout(cn);

					// 取选项
					TableLayout toselect = new TableLayout(cn);

					//
					final List listtemp = new ArrayList();

					for (final PubSeries ps1 : SO.getPubSeriesList()) {
						// 套餐里有几个菜品
						if (gp.equals(ps1.getSeriesgroupcode())
								&& ps1.getSeries_code().equals(sm.getCode())) {

							TextView subview = new TextView(cn);
							subview.setGravity(Gravity.CENTER);
							subview.setTextColor(R.color.loginbgcol);
							subview.setText(ps1.getSubmenu_name());
							subview.setPadding(3, 3, 3, 3);

							CheckBox cb = new CheckBox(cn);
							cb.setButtonDrawable(R.drawable.checkboxselector);
							cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
								@SuppressWarnings("unchecked")
								public void onCheckedChanged(
										CompoundButton buttonView,
										boolean isChecked) {

									BusSerieshit bsh = new BusSerieshit();
									bsh.setId(-1);
									bsh.setHit_code("-1");
									bsh.setSeries_code(ps1.getSeries_code());
									bsh.setSeriesgroupcode(ps1
											.getSeriesgroupcode());
									bsh.setSubmenu_code(ps1.getSubmenu_code());

									bsh.setAmount((int) ps1.getAmount());
									bsh.setUpload(0);
									bsh.setC1("");
									bsh.setC2("");
									bsh.setC3("");

									if (isChecked) {

										listtemp.add(ps1.getSubmenu_code());
										if (listtemp.size() > (int) psg
												.getSelectcount()) {
											buttonView.setChecked(false);
											listtemp.remove(ps1
													.getSubmenu_code());

										} else {

											bshlist.add(bsh);
										}
									} else {

										listtemp.remove(ps1.getSubmenu_code());

										// 使用Iterator替代增强型for循环,避免出错
										Iterator<BusSerieshit> iterator = bshlist
												.iterator();
										while (iterator.hasNext()) {
											BusSerieshit str = iterator.next();
											if (bsh.equals(str)) {
												iterator.remove();

											}
										}
									}

								}

							});

							to.addView(subview, new TableLayout.LayoutParams());
							toselect.addView(cb, new TableLayout.LayoutParams(
									LayoutParams.WRAP_CONTENT, 25));
						}
					}
					row.addView(iv, new LayoutParams(LayoutParams.MATCH_PARENT,
							2));
					row.addView(grpview, new TableRow.LayoutParams());
					row.addView(grpselect, new TableRow.LayoutParams());
					row.addView(to, new TableRow.LayoutParams());
					row.addView(toselect, new TableRow.LayoutParams());
					table.addView(row, new TableLayout.LayoutParams());
				}

				// 显示套餐组下的

			}

		}

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// 释放图片内存
		if (!bm.isRecycled()) {
			bm.recycle();
		}
	}

	

}
